package com.alibaba.nacossync.util;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.ListView;
import com.alibaba.nacos.api.utils.StringUtils;
import com.alibaba.nacossync.constant.SkyWalkerConstants;

import lombok.extern.slf4j.Slf4j;
/**
 * 
 * @author fenglibin
 * @date 2021年9月2日 下午5:32:04
 *
 */
@Slf4j
public class NacosUtil {
	/**
     * 从Nacos中获取所有的服务名称列表
     * @param groupName
     * @param sourceNamingService
     * @return
     */
    public static List<String> getAllNacosServiceNameList(String groupName, NamingService sourceNamingService){
    	List<String> servicesNameList = new ArrayList<String>();
    	int currentPage=SkyWalkerConstants.Page.FIRST_PAGE;
		int pageSize = SkyWalkerConstants.Page.DEFAULT_PAGE_SIZE;
		try {
			while(true) {
				ListView<String> serviceNameList = sourceNamingService.getServicesOfServer(currentPage, pageSize, StringUtils.isEmpty(groupName) ? Constants.DEFAULT_GROUP : groupName);
				if(serviceNameList != null && serviceNameList.getData() != null && serviceNameList.getData().size() > 0) {
					servicesNameList.addAll(serviceNameList.getData());
				}
				if(serviceNameList != null && serviceNameList.getData() != null && serviceNameList.getData().size() >=pageSize) {
					currentPage++;
				}else {
					break;
				}
			}
		}catch(Exception e) {
			log.error("Get service name list from nacos exception happened:"+e.getMessage(),e);
		}
		return servicesNameList;
    }
}
